package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.educational.discount.DiscountRegClassInfo;
import com.yuyou.fn.educational.discount.DiscountRegCourseClass;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.service.IAreaTeamBusTeamOrgService;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wens on 2017/7/21.
 */
@Controller
@RequestMapping("/api/admin/discount")
public class AdminDiscountController extends ApiBaseController {


    @Resource
    private IDiscountCategoryService discountCategoryService;

    @Resource
    private IDiscountRuleService discountRuleService;


    @Resource
    private IAreaTeamBusTeamOrgService areaTeamBusTeamOrgService;

    @Resource
    private IDiscountService discountService;

    @Resource
    private IStudentService studentService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private IDiscountCodeService discountCodeService;


    @ApiOperation("优惠分类列表")
    @RequestMapping(value = "/categoryList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<DiscountCategory>> categoryList(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<DiscountCategory> page = discountCategoryService.findDiscountCategory(pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("优惠分类详情")
    @RequestMapping(value = "/categoryDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<DiscountCategory> categoryDetail(@RequestParam("discountCategoryId") Long discountCategoryId) {
        DiscountCategory discountCategory = discountCategoryService.findById(discountCategoryId);
        return ReturnResult.success(discountCategory);
    }

    @ApiOperation("删除优惠分类")
    @RequestMapping(value = "/delCategory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> delCategory(@RequestParam("discountCategoryId") Long discountCategoryId) {
        discountCategoryService.delCategory(discountCategoryId);
        return ReturnResult.success("OK");
    }

    @ApiOperation("保存更新优惠分类")
    @RequestMapping(value = "/saveOrUpdateCategory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateCategory(@RequestParam(value = "discountCategoryId", required = false) Long discountCategoryId, @RequestParam("name") String name, HttpServletRequest request) {
        discountCategoryService.saveOrUpdateCategory(discountCategoryId, name);
        return ReturnResult.success("Ok");
    }


    @ApiOperation("优惠规则列表")
    @RequestMapping(value = "/ruleList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<DiscountRule>> ruleList(DiscountRuleQueryVo discountRuleQueryVo, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<DiscountRule> page = discountRuleService.findDiscountRuleByQuery(discountRuleQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("优惠规则详情")
    @RequestMapping(value = "/ruleDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<DiscountRule> ruleDetail(@RequestParam("discountRuleId") Long discountRuleId) {
        DiscountRule discountRule = discountRuleService.findById(discountRuleId);
        return ReturnResult.success(discountRule);
    }

    @ApiOperation("删除优惠规则")
    @RequestMapping(value = "/delRule", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> delRule(@RequestParam("discountRuleId") Long discountRuleId) {
        discountRuleService.deleteRule(discountRuleId);
        return ReturnResult.success("OK");
    }

    @ApiOperation("删除优惠规则")
    @RequestMapping(value = "/testData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<String> testData(@RequestParam("studentNos[]") List<String> studentNos, @RequestParam("classNos[]") List<String> classNos) {

        List<Student> studentList = studentService.findByStudentNos(studentNos);
        List<CourseClass> courseClassList = courseClassService.findByClassNo(classNos);
        List<DiscountRegClassInfo> discountRegClassInfoList = new ArrayList<>(courseClassList.size());
        for (CourseClass cc : courseClassList) {
            DiscountRegClassInfo regClassInfo = new DiscountRegClassInfo();
            BeanUtils.copyProperties(regClassInfo, cc);
            regClassInfo.setStartAmount(1);
            regClassInfo.setEndAmount(cc.getLectureAmount());
            regClassInfo.setTotalAmount(cc.getStudyingFee());
            discountRegClassInfoList.add(regClassInfo);
        }
        List<DiscountRegCourseClass> regCourseClassList = new ArrayList<>(studentList.size());
        for (Student student : studentList) {
            regCourseClassList.add(new DiscountRegCourseClass(student, discountRegClassInfoList));
        }

        String s = JSONObject.toJSONString(regCourseClassList, true);
        ReturnResult returnResult = ReturnResult.success();
        returnResult.setData(s);
        return returnResult;
    }

    @ApiOperation("删除优惠规则")
    @RequestMapping(value = "/testRule", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> testRule(@RequestParam("discountRuleId") Long discountRuleId, @RequestParam("params") String params, @RequestParam("testData") String testData) {
        String result = discountRuleService.testRule(discountRuleId, params, testData);
        ReturnResult ok = ReturnResult.success("OK");
        ok.setData(result);
        return ok;
    }

    @ApiOperation("保存更新优惠规则")
    @RequestMapping(value = "/saveOrUpdateRule", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateRule(DiscountRuleSaveOrUpdateVo discountRuleSaveOrUpdateVo, HttpServletRequest request) {
        discountRuleService.saveOrUpdateRule(discountRuleSaveOrUpdateVo);
        return ReturnResult.success("Ok");
    }


    @ApiOperation("优惠列表")
    @RequestMapping(value = "/discountList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<Discount>> discountList(DiscountQueryVo discountQueryVo, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        Page<Discount> page = discountService.findDiscountByQuery(discountQueryVo, getDataPermission(request), pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("优惠详情")
    @RequestMapping(value = "/discountDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Discount> discountDetail(@RequestParam("discountId") Long discountId) {
        Discount discount = discountService.findById(discountId);
        return ReturnResult.success(discount);
    }

    @ApiOperation("删除优惠")
    @RequestMapping(value = "/delDiscount", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> delDiscount(@RequestParam("discountId") Long discountId) {
        discountService.delDiscount(discountId);
        return ReturnResult.success("OK");
    }

    @ApiOperation("保存更新优惠规则")
    @RequestMapping(value = "/saveOrUpdateDiscount", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateDiscount(DiscountSaveOrUpdateVo discountSaveOrUpdateVo, HttpServletRequest request) {
        discountService.saveOrUpdateDiscount(discountSaveOrUpdateVo);
        return ReturnResult.success("Ok");
    }


    @ApiOperation("区域&业务结构")
    @RequestMapping(value = "/areaTeamBusTeamOrgTree", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<JSONArray> areaTeamBusTeamOrgTree(HttpServletRequest request) {
        JSONArray orgTree = areaTeamBusTeamOrgService.findOrgTree();
        return ReturnResult.success(orgTree);
    }


    @ApiOperation("优惠规则")
    @RequestMapping(value = "/discountRuleTree", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<JSONArray> discountRuleTree(HttpServletRequest request) {
        List<DiscountRule> discountRuleList = discountRuleService.findAll();
        Map<Long, List<DiscountRule>> discountRuleGroup = BeanUtils.toGroup(discountRuleList, "categoryId");
        List<DiscountCategory> discountCategoryList = discountCategoryService.findByIds(new ArrayList<Long>(discountRuleGroup.keySet()));

        JSONArray ret = new JSONArray();
        for (DiscountCategory discountCategory : discountCategoryList) {

            JSONObject o1 = new JSONObject();
            o1.put("categoryId", discountCategory.getDiscountCategoryId());
            o1.put("name", discountCategory.getName());

            List<DiscountRule> discountRulesList1 = discountRuleGroup.get(discountCategory.getDiscountCategoryId());
            if (discountRulesList1 != null && !discountRulesList1.isEmpty()) {
                JSONArray ret2 = new JSONArray();

                for (DiscountRule discountRule : discountRulesList1) {
                    JSONObject o2 = new JSONObject();
                    o2.put("ruleId", discountRule.getDiscountRuleId());
                    o2.put("name", discountRule.getName());
                    ret2.add(o2);
                }

                o1.put("ruleList", ret2);
            }
            ret.add(o1);
        }

        return ReturnResult.success(ret);
    }

    @ApiOperation("生成优惠码")
    @RequestMapping(value = "/createDiscountCode", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> createDiscountCode(@Valid DiscountCodeCreateVo discountCodeCreateVo) {
        discountCodeService.createDiscountCode(discountCodeCreateVo);
        return ReturnResult.success("OK");
    }

    @ApiOperation("优惠码列表")
    @RequestMapping(value = "/discountCodeList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<DiscountCode>> discountCodeList(DiscountCodeQueryVo discountCodeCreateVo, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        if (discountCodeCreateVo.getEndCreateTime() != null) {
            discountCodeCreateVo.setEndCreateTime(TimeUtils.changeOneDateLastTime(discountCodeCreateVo.getEndCreateTime()));
        }
        return ReturnResult.success(discountCodeService.findByQuery(discountCodeCreateVo, pageNo, pageSize));
    }

    @ApiOperation("批量更改优惠码启用状态")
    @RequestMapping(value = "/updateDiscountEnable", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> updateDiscountEnable(@RequestParam("discountCodeIds[]") List<Long> discountCodeIds, @RequestParam("enableStatus") Integer enableStatus) {
        discountCodeService.updateEnableStatus(discountCodeIds, enableStatus);
        return ReturnResult.success("OK");
    }


    @ApiOperation("导出优惠码列表")
    @RequestMapping(value = "/exportDiscountCodeList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void exportDiscountCodeList(DiscountCodeQueryVo discountCodeCreateVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (discountCodeCreateVo.getEndCreateTime() != null) {
            discountCodeCreateVo.setEndCreateTime(TimeUtils.changeOneDateLastTime(discountCodeCreateVo.getEndCreateTime()));
        }
        Page<DiscountCode> page = discountCodeService.findByQuery(discountCodeCreateVo, 1, 1024 * 10);

        SXSSFWorkbook excel = new SXSSFWorkbook();

        SXSSFSheet sheet = excel.createSheet("优惠码列表");

        SXSSFRow firstRow = sheet.createRow(0);

        String[] titles = new String[]{"优惠券名称", "优惠券码", "使用状态", "优惠类型", "优惠额度", "最低消费", "生效日期", "失效日期", "启用状态", "优惠券生成时间"};

        for (int i = 0; i < titles.length; i++) {

            SXSSFCell cell = firstRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        List<DiscountCode> discountCodes = page.getRecords();

        for (int i = 0; i < discountCodes.size(); i++) {

            SXSSFRow row = sheet.createRow(i + 1);

            DiscountCode discountCode = discountCodes.get(i);

            int c = 0;
            SXSSFCell cell = row.createCell(c++);
            cell.setCellValue(discountCode.getName());

            cell = row.createCell(c++);
            cell.setCellValue(discountCode.getCode());

            cell = row.createCell(c++);
            cell.setCellValue(EnumUtils.getName(DiscountCode.UsedStatusEnum.values(), discountCode.getUsedStatus()));

            cell = row.createCell(c++);
            cell.setCellValue(discountCode.getDiscountType() == 1 ? "折扣优惠" : "额度优惠");

            cell = row.createCell(c++);
            cell.setCellValue(BigDecimals.formatBigDecimal(discountCode.getDiscountAmount(), "0.00"));

            cell = row.createCell(c++);
            cell.setCellValue(BigDecimals.formatBigDecimal(discountCode.getOrderThresholdAmount(), "0"));

            cell = row.createCell(c++);
            cell.setCellValue(Utils.formatDate(discountCode.getEffectiveStartTime(), "yyyy-MM-dd HH:mm:ss"));

            cell = row.createCell(c++);
            cell.setCellValue(Utils.formatDate(discountCode.getEffectiveEndTime(), "yyyy-MM-dd HH:mm:ss"));

            cell = row.createCell(c++);
            cell.setCellValue(EnumUtils.getName(DiscountCode.EnableStatusEnum.values(), discountCode.getEnableStatus()));

            cell = row.createCell(c++);
            cell.setCellValue(Utils.formatDate(discountCode.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));

        }
        Webs.writeExcel(request, response, excel, "优惠码");

    }


}
